const Koa = require('koa')
const KoaRouter = require('koa-router')
const KoaJson = require('koa-json')
const KoaBody = require('koa-body')
const KoaCors = require('@koa/cors')

const koa = new Koa()
const koaRouter = new KoaRouter()

koaRouter.prefix('/api')

koaRouter.post('/user', async (ctx) => {
    let {body} = ctx.request
    let role = ctx.request.header.role 
    console.log(body)
    if (!role || role != 'admin') {
        ctx.body = {
            code: 401,
            message: 'unauthorized post'
        }
    }else{
        if (body.name && body.email) {
            ctx.body = {
                code: 200,
                data: body,
                message: '上传成功'
            }
        }else {
            ctx.body = {
                code: 404,
                message: 'name与email不得为空'
            }
        }
    }
})

koa.use(KoaBody())
koa.use(KoaCors())
koa.use(KoaJson({pretty:false, params: 'pretty'}))
koa.use(koaRouter.routes()).use(koaRouter.allowedMethods())

koa.listen(3000)